package com.ysd.lis.controller.bac;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ysd.common.Result;
import com.ysd.lis.controller.pub.BaseController;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.BacAddFee;
import com.ysd.lis.entity.bac.BacDrugTestResult;
import com.ysd.lis.entity.lab.LabFeeItem;
import com.ysd.lis.entity.lab.LabReqMain;
import com.ysd.lis.mapper.bac.BacDrugTestResultMapper;
import com.ysd.lis.mapper.lab.LabReqMainMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.DeleteParam;
import com.ysd.lis.service.bac.BacAddFeeService;
import com.ysd.lis.service.lab.LabFeeItemService;
import com.ysd.util.RedisUserManager;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 抗生素 前端控制器
 * </p>
 *
 * @author pc
 * @since 2024-01-11
 */
@RestController
@RequestMapping("/bac/addFee")
public class BacAddFeeController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BacAddFeeController.class);

    @Autowired
    private BacAddFeeService bacAddFeeService;
    @Autowired
    private LabFeeItemService labFeeItemService;
    @Autowired
    private SysInterfaceMapper sysInterfaceMapper;
    @Autowired
    BacDrugTestResultMapper bacDrugTestResultMapper;
    @Autowired
    LabReqMainMapper labReqMainMapper;

    @ApiOperation("获取费用补录项目")
    @GetMapping("/findBacAddFeeItem")
    public Result findBacAddFeeItem(String feeCodes) {
        LambdaQueryWrapper<LabFeeItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabFeeItem::getFeeClass, "1")
                .eq(LabFeeItem::getDelFlag, 0);
        List<LabFeeItem> list = labFeeItemService.list(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", list);
    }

    @ApiOperation("获取费用补录")
    @GetMapping("/findBacAddFeeByMainInfo")
    public Result findBacAddFeeByMainInfo(BacAddFee bacAddFee) {
        LambdaQueryWrapper<BacAddFee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BacAddFee::getRptGroup, bacAddFee.getRptGroup())
                .eq(BacAddFee::getSampleNo, bacAddFee.getSampleNo())
                .eq(BacAddFee::getSampleda, bacAddFee.getSampleda())
                .eq(BacAddFee::getDelFlag, 0);
        List<BacAddFee> list = bacAddFeeService.list(lambdaQueryWrapper);
        //查看上机记录是否有抗生素

        LambdaQueryWrapper<BacDrugTestResult> queryWrapperMR = new LambdaQueryWrapper<>();
        queryWrapperMR.eq(BacDrugTestResult::getDelFlag, 0)
                .eq(BacDrugTestResult::getSampleNo, bacAddFee.getSampleNo())
                .eq(BacDrugTestResult::getRptGroup, bacAddFee.getRptGroup());
        if (!BeanUtil.isEmpty(bacAddFee.getSampleda())) {
            Timestamp startTime = Timestamp.valueOf(bacAddFee.getSampleda().toString().substring(0, 10) + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(bacAddFee.getSampleda().toString().substring(0, 10) + " 23:59:59");
            queryWrapperMR.ge(BacDrugTestResult::getSampleda, startTime);
            queryWrapperMR.le(BacDrugTestResult::getSampleda, endTime);
        }
        Integer bacDrugCnt = bacDrugTestResultMapper.selectCount(queryWrapperMR);
        Map returnMap = new HashMap<>();
        returnMap.put("bacDrugCnt", bacDrugCnt);
        returnMap.put("bacAddFeeList", list);

        return Result.succ(1, "查询成功", returnMap);
    }

    @ApiOperation("批量新增补费记录")
    @PostMapping("/batchAddFeeList")
    public Result batchAddFeeList(@RequestBody List<BacAddFee> list) {
        if (StrUtil.isEmpty(list.get(0).getReqNo())) {
            return Result.fail("申请单号为空，计费失败");
        }
        LambdaQueryWrapper<LabReqMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabReqMain::getReqNo, list.get(0).getReqNo())
                .eq(LabReqMain::getDelFlag, 0);
        List<LabReqMain> labReqMains = labReqMainMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(labReqMains)) {
            return Result.fail("申请单号不存在，计费失败");
        }
        String reqDept = labReqMains.get(0).getReqDept();
        SysUser sysUser = RedisUserManager.getUser();
        list.forEach(a -> {
            if (StrUtil.isNotEmpty(a.getId())) {
                a.setAddUser(sysUser.getUsername());
                a.setRemark1(sysUser.getRealname());
                a.setAddTime(Timestamp.valueOf(LocalDateTime.now()));
                a.setIsCharge(1);
                a.setReqDept(reqDept);
                bacAddFeeService.updateById(a);
            } else {
                a.setAddUser(sysUser.getUsername());
                a.setRemark1(sysUser.getRealname());
                a.setAddTime(Timestamp.valueOf(LocalDateTime.now()));
                a.setIsCharge(1);
                a.setReqDept(reqDept);
                bacAddFeeService.save(a);
            }
        });
        //调用计费接口
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

//            String updateUrl = "http://localhost:5004/bacAddFee";
//            logger.info("开始执行微生物补费接口:" + JSONUtil.toJsonStr(list));
//            HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(list)).contentType("application/json").execute().body();

        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
            /*发布报告相关*/
            for (String webUrl : collect) {
                //调用修改状态接口
                String updateUrl = webUrl + "/bacAddFee";
                logger.info("开始执行微生物补费接口:" + JSONUtil.toJsonStr(list));
                HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(list)).contentType("application/json").execute().body();
            }
        }
        return Result.succ(1, "添加成功", "");
    }


    @ApiOperation("批量新增补费记录")
    @PostMapping("/countFeeItemsNum")
    public Result countFeeItemsNum(@RequestBody List<BacAddFee> list) {
        //查询出该病人下所有的药敏结果
        LambdaQueryWrapper<BacDrugTestResult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BacDrugTestResult::getDelFlag, 0)
                .eq(BacDrugTestResult::getSampleNo, list.get(0).getSampleNo())
                .eq(BacDrugTestResult::getRptGroup, list.get(0).getRptGroup())
                .eq(BacDrugTestResult::getSampleda, list.get(0).getSampleda());
        List<BacDrugTestResult> bacDrugTestResults = bacDrugTestResultMapper.selectList(lambdaQueryWrapper);

        for (BacAddFee bacAddFee : list) {
            bacAddFee.setAmount(new BigDecimal(bacDrugTestResults.size()));
            bacAddFee.setCosts(new BigDecimal(bacDrugTestResults.size()).multiply(bacAddFee.getPrice()));
        }
        return Result.succ(1, "计算成功", list);
    }


    @ApiOperation("修改补费记录")
    @PostMapping("/editFee")
    public Result editFee(@RequestBody BacAddFee bacAddFee) {
        boolean b = bacAddFeeService.updateById(bacAddFee);
        if (b) {
            return Result.succ(1, "修改成功", "");
        }
        return Result.fail(400, "修改失败", "");
    }

    @ApiOperation("根据id删除补费信息")
    @PostMapping("/deleteAddFee")
    public Result deleteAddFee(@RequestBody DeleteParam deleteParam) {
        SysUser sysUser = RedisUserManager.getUser();
        String[] split = deleteParam.getIds().split(",");
        List<BacAddFee> bacAddFees = bacAddFeeService.listByIds(Arrays.asList(split));
        bacAddFees.forEach(a -> {
            a.setAddUser(sysUser.getUsername());
            a.setAmount(a.getAmount().negate());
        });
        //调用退费接口
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
            /*发布报告相关*/
            for (String webUrl : collect) {
                //调用修改状态接口
                String updateUrl = webUrl + "/bacReturnFee";
                List<BacAddFee> collect1 = bacAddFees.stream().filter(o -> o.getIsCharge() == 1).collect(Collectors.toList());
                logger.info("开始执行微生物补费退费接口:" + JSONUtil.toJsonStr(collect1));
                HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(collect1)).contentType("application/json").execute().body();
            }
        }
        boolean b = bacAddFeeService.removeByIds(Arrays.asList(split));
        if (b) {
            return Result.succ(1, "删除成功", "");
        }
        return Result.fail(400, "删除失败", "");
    }
}
